import time

from appium.webdriver.common.touch_action import TouchAction
from loguru import logger
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait
from selenium import webdriver as chromedriver
from selenium.webdriver.chrome.options import Options
from common.yaml_util import read_yaml
from appium import webdriver as appium_driver
from appium.webdriver.common.appiumby import AppiumBy


if read_yaml('系统配置.yaml')['驱动'] == 'selenium':
    chrome_options = Options()  # 不知道干啥的，但是要有
    chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")  # 与上发的端口相同
    chrome_driver = Service("E:\\driver\\chromedriver.exe")  # 加载浏览器启动器
    wd = chromedriver.Chrome(service=chrome_driver, options=chrome_options)

    class Element:
        def __init__(self, args):
            try:
                logger.info("获取元素： - %s" % args[1])
                element = WebDriverWait(wd, 30).until(
                    # 判断所定位的元素是否可见且可点击
                    ec.element_to_be_clickable(args)  # 等待元素出现
                )
                self.element = element
            except Exception as e:
                raise "无法定位指定元素"

        def send_keys(self, value):
            self.element.send_keys(value)
            logger.info('输入文本：%s' % value)

        def click(self):
            self.element.click()

        def clear(self):
            self.element.clear()

        def text(self):
            value = self.element.text
            logger.info('获取文本：%s' % value)
            return value

    def get(url):
        wd.get(url)

    def sleep(second):
        time.sleep(second)
        logger.info("睡眠%s秒" % str(second))

    def switch_to_frame(args):
        if is_display(args, on_click=False):
            wd.switch_to.frame(Element(args).element)
            logger.info("切换完成 - %s" % args[1])
        else:
            logger.warning("未找到frame")

    def quit_frame():
        wd.switch_to.default_content()
        logger.info("切出frame")

    def refresh():
        wd.refresh()
        logger.info("刷新页面")

    def is_display(args, on_click=True):
        flag = True
        loc = args[1]
        try:
            element = wd.find_element(*args)
            if element.is_enabled() and "{'height': 0, 'width': 0}" != str(element.size):
                logger.info("元素-%s：存在" % loc)
                if on_click:
                    element.click()
            else:
                flag = False
                logger.warning("元素-%s：存在但不可见" % loc)
        except Exception:
            logger.warning("元素-%s：不存在：" % loc)
            return False
        return flag

    def wait_for_load(args):
        num = 0
        while num < 3:
            sleep(3)
            if is_display(args):
                return
            num += 1
else:
    desired_caps = {
        'platformName': 'Android',  # 被测手机是安卓
        'platformVersion': '11',  # 手机安卓版本
        'deviceName': '',  # 设备名，安卓手机可以随意填写
        'appPackage': 'com.ecology.view',  # 启动APP Package名称
        'appActivity': 'com.ecology.view.WelcomeActivity',  # 启动Activity名称
        'unicodeKeyboard': True,  # 使用自带输入法，输入中文时填True
        'resetKeyboard': True,  # 执行完程序恢复原来输入法
        'noReset': True,  # 不要重置App
        'newCommandTimeout': 6000,
        # 'app': r'd:\apk\bili.apk',
    }
    driver = appium_driver.Remote('http://localhost:4723/wd/hub', desired_caps)
    # 设置缺省等待时间
    driver.implicitly_wait(10)

    class Element:
        def __init__(self, loc=None, args=None):
            try:
                args = (AppiumBy.ANDROID_UIAUTOMATOR, loc) if args is None else args
                self.element = driver.find_element(*args)
                self.actions = TouchAction(driver)
            except Exception as e:
                raise "无法定位指定元素"

        def send_keys(self, value):
            self.element.send_keys(value)
            logger.info('输入文本：%s' % value)

        def click(self):
            self.element.click()

        def long_press(self, duration):
            self.actions.long_press(self.element, duration).release().perform()

        # 移动
        def move_to(self, x=None, y=None):
            self.actions.move_to(self.element, x, y).release().perform()

    def get_elements(loc):
        return driver.find_elements(AppiumBy.ANDROID_UIAUTOMATOR, loc)

    def tap(coord, dwell_time):
        driver.tap([coord], dwell_time)
        logger.info('点击：%s %d毫秒' % (coord, dwell_time))

    # 滑动
    def swipe(start_coord, end_coord, duration=800):
        driver.swipe(start_x=start_coord[0], start_y=start_coord[1], end_x=end_coord[0], end_y=end_coord[1], duration=duration)

    # 键入， 如果有需要可以将AndroidKey中对应的数字做成字典
    def enter(key_ls):
        for key in key_ls:
            driver.press_keycode(key)
